var restorePoints = [];
$(document)
		.ready(
				function() {
					var restorePoints = [];
					var a = false;
					var b, c = "";
					var d = document.getElementById("doodle");
					var e = d.getContext("2d");
					e.strokeStyle = "red";
					e.lineWidth = 6;
					e.lineCap = "round";
					e.fillStyle = "#fff";
					e.fillRect(0, 0, d.width, d.height);
					/*$("#bsz").change(function(a) {
						e.lineWidth = this.value;
					});*/
					$("#bcl").change(function(a) {
						e.strokeStyle = this.value;
					});
					$("#doodle").mousedown(function(d) {
						//saveRestorePoint();
						a = true;
						e.save();
						pos = $(this).offset();
						b = d.pageX - pos.left;
						c = d.pageY - pos.top;
					});
					$(document).mouseup(function() {
						a = false;
					});
					$(document).click(function() {
						a = false;
					});
					$("#doodle").mousemove(
							function(d) {
								if (a == true) {
									pos = $(this).offset();
									e.beginPath();
									e.moveTo(d.pageX - pos.left, d.pageY
											- pos.top);
									e.lineTo(b, c);
									e.stroke();
									e.closePath();
									b = d.pageX - pos.left;
									c = d.pageY - pos.top;
								}
							});

					$(".doodleAction > a").click(function() {
						$(".doodleAction > a").removeClass("active");
						$(this).addClass("active");
						e.strokeStyle = $(this).attr("dc");
						$("#doodleEraser").removeClass("active");
					});
					$(".doodleSize > a").click(function() {
						$(".doodleSize > a").removeClass("active");
						$(this).addClass("active");
						e.lineWidth = $(this).attr('ds');
					});
					/*$("#undo").click(function() {
						undoDrawOnCanvas();
					});*/
					$("#doodleEraser").click(function() {
						if($(this).is(".active")) {
							var cl = $(".doodleAction > a.active").attr("dc");
							e.strokeStyle = cl;
							$(this).removeClass("active");
						}
						else {
							e.strokeStyle = "#fff";
							$(this).addClass("active");
						}
					});
					$("#doodleClear").click(function() {
						e.fillStyle = "#fff";
						e.fillRect(0, 0, d.width, d.height);
						e.strokeStyle = "red";
						e.fillStyle = "red";
						
						$(".doodleAction > a")[1].click();
					});
				});
function saveRestorePoint() {
	var oCanvas = document.getElementById("doodle");
	var imgSrc = oCanvas.toDataURL("image/png");
	restorePoints.push(imgSrc);
}

function undoDrawOnCanvas() {
	if (restorePoints.length > 0) {
		var oImg = new Image();
		oImg.onload = function() {
			var canvasContext = document.getElementById("doodle").getContext("2d");
			canvasContext.drawImage(oImg, 0, 0);
		}
		oImg.src = restorePoints.pop();
	}
}